package agents

import (
	"context"
	"k8sops/pkg/client"
	"log"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func GetPodResource(pod v1.Pod, namespace string) (cpu, memory int64) {
	k := client.K8sClientSet{}
	c, err := k.GetMetricsClientset()
	if err != nil {
		log.Fatal(err.Error())
		return
	}

	if pod.Status.Phase != "Running" {
		return
	}
	for _, containerStatus := range pod.Status.ContainerStatuses {
		if !containerStatus.Ready {
			return
		}
	}

	podMetrics, err := c.MetricsV1beta1().PodMetricses(namespace).Get(context.TODO(), pod.Name, metav1.GetOptions{})
	if err != nil {
		log.Fatal(err.Error(), pod.Status.Phase)
		return
	}
	for _, container := range podMetrics.Containers {
		cpuUsage := container.Usage[v1.ResourceCPU]
		memUsage := container.Usage[v1.ResourceMemory]

		cpu += cpuUsage.MilliValue() // CPU usage in millicores
		memory += memUsage.Value()   // Memory usage in bytes
	}

	return
}
